//
//  KSBLEManager.m
//  ROCOMO
//
//  Created by Kyle Sun on 5/12/16.
//  Copyright © 2016 ROCOMO. All rights reserved.
//

#import "KSBLEManager.h"
#import "IMTCarManager.h"
#import "BleNameCheck.h"

NSString * const KSBLEPeripheralInfoPeripheralKey = @"KSBLEPeripheralInfoPeripheralKey";
NSString * const KSBLEPeripheralInfoRSSIKey = @"KSBLEPeripheralInfoRSSIKey";
NSString * const KSBLEManagerErrorDomain = @"KSBLEManagerErrorDomain";

const NSInteger kKSBLEPacketSize = 20;  /// 每包数据的大小 - 因硬件所采用的蓝牙版本不同新车型可以发送182字节，旧车型只能发送20字节。可通过maximumWriteValueLengthForType获取后设置。

@interface KSBLEManager()<CBCentralManagerDelegate, CBPeripheralDelegate>

@property (nonatomic, strong, readwrite) NSMutableArray *discoveredPeripherals;         //!< 发现的设备数组
@property (nonatomic, assign, readwrite) KSBLEManagerState state;                       //!< 蓝牙的状态
@property (nonatomic, strong) CBPeripheral *connectingPeripheral;                       //!< 正在连接的设备
@property (nonatomic, strong) NSArray *storedServices;                                  //!< 存储的服务
@property (nonatomic, strong) NSArray *readableCharacteristics;                         //!< 可读特征数组
@property (nonatomic, strong) NSArray *writableCharacteristics;                         //!< 可写特征数组
@property (nonatomic, strong) CBCharacteristic *writableCharacteristic;                 //!< 写特征
@property (nonatomic, weak) id<KSBLEManagerDelegate> delegate;                          //!< 代理 （暂不用)
@property (nonatomic, strong) CBCentralManager *centralManager;                         //!< 中心管理
@property (nonatomic, copy) KSBLEManagerConnectionSuccessBlock connectionSuccessBlock;  //!< 连接成功block
@property (nonatomic, copy) KSBLEManagerConnectionFailureBlock connectionFailureBlock;  //!< 连接失败block
@property (nonatomic, strong) NSTimer *timer;                                           //!< 连接超时time
@property (nonatomic, strong) NSMutableDictionary *stateChangeBlocks;                   //!< 状态改变block
@property (nonatomic, copy, readwrite) NSString *macAdress;                             //!< mac 地址

@property (nonatomic, assign) NSUInteger packetLength;

@end

@implementation KSBLEManager

+ (instancetype)sharedManager {
    static KSBLEManager *_sharedInstance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedInstance = [[KSBLEManager alloc] init];
    });
    return _sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.uploading = @"未升级";
        // 所有服务
        NSArray *services = @[[CBUUID UUIDWithString:DEVICE_INFO_SERVICE_UUID],
                              [CBUUID UUIDWithString:SEND_SERVICE_UUID],
                              [CBUUID UUIDWithString:SEND_SERVICE_UUID_NEW],
                              [CBUUID UUIDWithString:RECEIVE_SERVICE_UUID],
                              [CBUUID UUIDWithString:RECEIVE_SERVICE_UUID_NEW]];
        
        // 所有读特征
        NSArray *readableCharacteristics = @[[CBUUID UUIDWithString:DEVICE_INFO_CHAR_UUID],
                                             [CBUUID UUIDWithString:RECEIVE_CHAR_UUID],
                                             [CBUUID UUIDWithString:RECEIVE_CHAR_UUID_NEW]];
        
        // 所有写特征
        NSArray *writableCharacteristics = @[[CBUUID UUIDWithString:SEND_CHAR_UUID],
                                             [CBUUID UUIDWithString:SEND_CHAR_UUID_NEW]];
        self.storedServices = services;
        self.readableCharacteristics = readableCharacteristics;
        self.writableCharacteristics = writableCharacteristics;
        self.discoveredPeripherals = [NSMutableArray arrayWithCapacity:1];
        self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:@{CBCentralManagerOptionShowPowerAlertKey: @NO}];
    }
    return self;
}
//
//#pragma mark 开始扫描
- (void)startScanWithWithDuration:(NSTimeInterval)time completion:(KSBLEManagerScanCompletionBlock)completion {
    
    if (self.state != KSBLEManagerStateReady && self.state != KSBLEManagerStateIdle) {
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeWrongState userInfo:nil];
        completion(error,nil);
        return;
    }
    [self.discoveredPeripherals removeAllObjects];

    if (self.centralManager.state == CBCentralManagerStatePoweredOn) {
        self.state = KSBLEManagerStateScanning;

        /// 旧版指定服务进行搜索
         NSMutableArray *services = [self.storedServices mutableCopy];
         [services addObject:[CBUUID UUIDWithString:PERIPHERAL_UUID]];
        NSUserDefaults *userDF = [NSUserDefaults standardUserDefaults];
        BOOL isUserService = [userDF boolForKey:@"isUserService"];
        if (!isUserService) {
            services = nil;
        }
        /// 开始搜索 -- 不指定服务
        [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}];

    } else if (self.centralManager.state == CBCentralManagerStatePoweredOff) {
        self.state = KSBLEManagerStateUnavailable;
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeBluetoothPoweredOff userInfo:nil];
        completion(error, nil);
    } else {
        self.state = KSBLEManagerStateUnavailable;
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeBluetoothUnavailable userInfo:nil];
        completion(error, nil);
    }

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self stopScan];
//        if (self.discoveredPeripherals.count) {
            if (completion) {
                completion(nil, self.discoveredPeripherals.copy);
            }
//        }else {
//            self.state = KSBLEManagerStateReady;
//            NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeSacnTimeout userInfo:nil];
//            completion(error,nil);
//        }
    });

}


#pragma mark 开始扫描
- (void)startScanWithBlock:(KSBLEManagerScanCompletionBlock)completion {
    self.didScanPeripherals = completion;
    if (self.state != KSBLEManagerStateReady && self.state != KSBLEManagerStateIdle) {
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeWrongState userInfo:nil];
        completion(error,nil);
        return;
    }
    [self.discoveredPeripherals removeAllObjects];

    if (self.centralManager.state == CBCentralManagerStatePoweredOn) {
        self.state = KSBLEManagerStateScanning;

        /// 旧版指定服务进行搜索
         NSMutableArray *services = [self.storedServices mutableCopy];
         [services addObject:[CBUUID UUIDWithString:PERIPHERAL_UUID]];
        NSUserDefaults *userDF = [NSUserDefaults standardUserDefaults];
        BOOL isUserService = [userDF boolForKey:@"isUserService"];
        if (!isUserService) {
            services = nil;
        }
        /// 开始搜索 -- 不指定服务
        [self.centralManager scanForPeripheralsWithServices:nil options:@{CBCentralManagerScanOptionAllowDuplicatesKey: @YES}];
        
    } else if (self.centralManager.state == CBCentralManagerStatePoweredOff) {
        self.state = KSBLEManagerStateUnavailable;
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeBluetoothPoweredOff userInfo:nil];
        completion(error, nil);
    } else {
        self.state = KSBLEManagerStateUnavailable;
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeBluetoothUnavailable userInfo:nil];
        completion(error, nil);
    }

}

#pragma mark 停止搜索
- (void)stopScan {
    if (self.state == KSBLEManagerStateScanning) {
        self.state = KSBLEManagerStateIdle;
    }
    [self.centralManager stopScan];
}

#pragma mark 连接设备
- (void)connectPeripheral:(CBPeripheral *)peripheral success:(KSBLEManagerConnectionSuccessBlock)success failure:(KSBLEManagerConnectionFailureBlock)failure {
    [self stopScan];
    self.state = KSBLEManagerStateConnecting;
    self.connectionSuccessBlock = success;
    self.connectionFailureBlock = failure;
    self.connectingPeripheral = peripheral;
    [self.centralManager connectPeripheral:peripheral options:nil];
   
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:6 target:self selector:@selector(connectionTimeout) userInfo:nil repeats:false];
}

#pragma mark 连接超时操作
- (void)connectionTimeout {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    [self cancelConnection:self.connectingPeripheral];
    self.state = KSBLEManagerStateIdle;
    NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeConnectionTimeout userInfo:@{NSLocalizedDescriptionKey:@"Connection timed out"}];
    self.connectionFailureBlock(error);
    self.connectingPeripheral = nil;
    self.connectionFailureBlock = nil;
    self.connectionSuccessBlock = nil;
}

#pragma mark 添加状态改变block
- (void)addStateChangeBlock:(KSBLEManagerStateChangeBlock)block forKey:(NSString *)key {
    if (!_stateChangeBlocks) {
        _stateChangeBlocks = [NSMutableDictionary dictionaryWithCapacity:1];
    }
    [_stateChangeBlocks setObject:[block copy] forKey:key];
}

#pragma mark 删除状态改变block
- (void)removeStateChangeBlockForKey:(NSString *)key {
    [_stateChangeBlocks removeObjectForKey:key];
}

#pragma mark 取消连接设备
- (void)cancelConnection:(CBPeripheral *)peripheral {
    if (self.state == KSBLEManagerStateConnecting ||
        self.state == KSBLEManagerStateConnected ||
        self.state == KSBLEManagerStateSubscribed) {
        [self.centralManager cancelPeripheralConnection:peripheral];
    } else {
        NSLog(@"KSBLEManager想要断开连接，但是并不是连接中到已订阅状态。。。");
    }
}

#pragma mark 断开连接
- (void)disconnect {
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    self.state = KSBLEManagerStateIdle;

    if (self.connectingPeripheral) {
        [self.centralManager cancelPeripheralConnection:self.connectingPeripheral];
    }
    if (self.connectedPeripheral) {
        [self.centralManager cancelPeripheralConnection:self.connectedPeripheral];
    }
}

#pragma mark 发送数据
- (void)sendData:(NSData *)data {
    if (data == nil || data.length == 0) {
        return;
    }

    NSInteger sendedIndex = 0;
    for (int i = 0; i < data.length; i++) {
        if (sendedIndex < data.length) {
            NSInteger size = data.length - sendedIndex;
            if (size > self.packetLength) {
                size = self.packetLength;  /// 每次发20字节或超出20字节，根据硬件判断
            }
            NSRange range = NSMakeRange(sendedIndex, size);
            NSData *chunk = [data subdataWithRange:range];
            if (!self.writableCharacteristic) {
                return;
            }
            [self.connectedPeripheral writeValue:chunk
                               forCharacteristic:self.writableCharacteristic
                                            type:CBCharacteristicWriteWithoutResponse];
            sendedIndex += size;
            NSLog(@"发送蓝牙数据 ==== :%@",chunk);
        } else {
            break;
        }
    }
}

#pragma mark 处理发现外设
- (void)handleDiscoveredPeripheral:(CBPeripheral *)discoveredPeripheral RSSI:(NSNumber *)RSSI {

    BOOL contains = NO;
    for (CBPeripheral *peripheral in self.discoveredPeripherals) {
        if ([discoveredPeripheral.identifier.UUIDString isEqualToString:peripheral.identifier.UUIDString]) {
            contains = YES;
            return;
        }
    }

    if (!contains) {
        // 正则判断
        NSString *bleName = @"^(R|E|L|P|S|V|Glide|D|B|Lively|IM)([0-9]{0,3}|[A-Z]{1})([A-Za-z]{0,4}|[+]|Lite)-([0-9A-F]{8}|[0-9A-F]{12})$";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",bleName];
        // 字符串判断，然后BOOL值
        BOOL result = [predicate evaluateWithObject:discoveredPeripheral.name];
//        result = YES;
        if (discoveredPeripheral.name.length == 0) {
            result = NO;
        }
        
        /// 判断是否以L9开头
        /// 新增S1车型 —2022.3.25
        result = [BleNameCheck isSupported:discoveredPeripheral.name];
        NSLog(@"发现外设 name : %@ - %d", discoveredPeripheral.name, result);
        if (![self.discoveredPeripherals containsObject:discoveredPeripheral] && result) {
            NSLog(@"发现外设 :%@----RSSI:%@", discoveredPeripheral,RSSI);
           [self.discoveredPeripherals addObject:discoveredPeripheral];
            
            if (self.didScanPeripherals) {
                self.didScanPeripherals(nil, self.discoveredPeripherals.copy);
            }
        }
    }
}

#pragma mark 设置蓝牙状态，回调蓝牙状态修改block
- (void)setState:(KSBLEManagerState)state {
    _state = state;
    NSString *s = nil;
    switch (state) {
        case KSBLEManagerStateUnavailable:
            s = @"KSBLEManagerStateUnavailable";
            break;
        case KSBLEManagerStateReady:
            s = @"KSBLEManagerStateReady";
            break;
        case KSBLEManagerStateIdle:
            s = @"KSBLEManagerStateIdle";
            break;
        case KSBLEManagerStateScanning:
            s = @"KSBLEManagerStateScanning";
            break;
        case KSBLEManagerStateConnecting:
            s = @"KSBLEManagerStateConnecting";
            break;
        case KSBLEManagerStateConnected:
            s = @"KSBLEManagerStateConnected";
            break;
        case KSBLEManagerStateSubscribed:
            s = @"KSBLEManagerStateSubscribed";
            break;
        default:
            break;
    }
    NSLog(@"蓝牙状态: %@", s);
    for (KSBLEManagerStateChangeBlock block in _stateChangeBlocks.allValues) {
        block(state);
    }
}

#pragma mark 已经连接
- (BOOL)connected {
    return _state == KSBLEManagerStateSubscribed;
}

#pragma mark - CentralManagerDelegate
#pragma mark 手机蓝牙状态改变回调
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            if (self.state == KSBLEManagerStateUnavailable) {
                self.state = KSBLEManagerStateReady;
            } else {
                NSLog(@"KSBLEManager未知蓝牙状态。。。");
            }
            break;
        default:
            self.state = KSBLEManagerStateUnavailable;
            break;
    }
}

#pragma mark 发现外设回调
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
    [self handleDiscoveredPeripheral:peripheral RSSI:RSSI];
}

#pragma mark 连接上外设回调
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
    peripheral.delegate = self;
    self.state = KSBLEManagerStateConnected;
    // 连接上后设置默认最大传输子节数为20.
    self.packetLength = kKSBLEPacketSize;
    NSLog(@"============ c扫描服务");
    // 连接外设后发现该外设的服务
    [peripheral discoverServices:self.storedServices];
}

#pragma mark 连接外设失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"连接失败 :%@", [error localizedDescription]);
    if (self.state == KSBLEManagerStateConnecting) {
        if (self.timer) {
            [self.timer invalidate];
            self.timer = nil;
        }
        self.state = KSBLEManagerStateIdle;
        NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeConnectionFailed userInfo:@{NSLocalizedDescriptionKey:@"connection_failed"}];
        self.connectionFailureBlock(error);
        self.connectionFailureBlock = nil;
        self.connectionSuccessBlock = nil;
    } else {
        NSLog(@"KSBLEManager连接失败，但是状态不是连接中");
    }
}

#pragma mark 设备连接断开了
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
    NSLog(@"KSBLEManager disconnected :%@", error);
//    [self.centralManager connectPeripheral:peripheral options:nil]; /// 断开自动重连

    if (self.state == KSBLEManagerStateConnected) {
        if (self.connectionFailureBlock) {
            self.state = KSBLEManagerStateIdle;
            NSError *error = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeAutoDisconnected userInfo:@{NSLocalizedDescriptionKey:@"AutoDisconnected"}];
            [self.timer invalidate];
            self.connectionFailureBlock(error);
            self.connectionFailureBlock = nil;
            self.connectionSuccessBlock = nil;
        } else {
            NSLog(@"KSBLEManager断开连接，但是不是已连接状态");
        }
    } else if (self.state == KSBLEManagerStateSubscribed) {
        self.state = KSBLEManagerStateReady;
    } else {
        NSLog(@"KSBLEManager断开连接，但是不是已连接状态");
    }
}

#pragma mark - PeriphralDelegate
#pragma mark 发现服务回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
    NSLog(@"🌹设备所有的服务 ================== %@",peripheral.services);
    if (self.state != KSBLEManagerStateConnected) {
        NSLog(@"KSBLEManager发现服务，但是不是已连接状态。。。");
        return;
    }
    for (CBService *service in peripheral.services) {
        // 合并两个数组避免 `didDiscoverCharacteristicsForService` 调用两次
        NSMutableArray *chars = [self.readableCharacteristics mutableCopy];
        [chars addObjectsFromArray:self.writableCharacteristics];
        // 发现读写特征
        [peripheral discoverCharacteristics:chars forService:service];
    }
}

#pragma mark 发现特征回调
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    NSLog(@"🌹设备所有的特征 ================== %@",service.characteristics);

    if (self.state != KSBLEManagerStateConnected) {
        NSLog(@"KSBLEManager发现特征值，但是不是已连接状态。。。");
        return;
    }
    for (CBCharacteristic *characteristic in service.characteristics) {
        
        if ([characteristic.UUID isEqual:self.readableCharacteristics.firstObject]){ /// 获取Mac地址 - 后台添加车辆需要
            [peripheral readValueForCharacteristic:characteristic];
            continue;
        }
        for (CBUUID *UUID in self.readableCharacteristics) {
            if ([characteristic.UUID isEqual:UUID]) {
                // 订阅读特征:
                [peripheral setNotifyValue:YES forCharacteristic:characteristic];
                break;
            }
        }
        for (CBUUID *UUID in self.writableCharacteristics) {
            if ([characteristic.UUID isEqual:UUID]) {
                // 保存写特征：
                self.writableCharacteristic = characteristic;
                break;
            }
        }
    }
}

#pragma mark 更新特征回调
- (void)peripheral:(CBPeripheral *)peripheral didUpdateNotificationStateForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (self.state != KSBLEManagerStateConnected) {
        NSLog(@"KSBLEManager订阅回调，但是状态不对...");
        return;
    }
    if (error) {
        NSLog(@"更新特征回调 错误 - %@", [error localizedDescription]);
        return;
    }
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }

    if ([self.readableCharacteristics containsObject:characteristic.UUID]) {
        if (characteristic.isNotifying) {
            NSLog(@" -- 订阅特征成功 -- ");
            if (self.connectionSuccessBlock) {
                self.state = KSBLEManagerStateSubscribed;
                self.connectedPeripheral = peripheral;
                
                 //判断当前外设的蓝牙版本所支持的最大传输子节数。 -- 暂不处理。
                 NSUInteger datalenth = [peripheral maximumWriteValueLengthForType:(CBCharacteristicWriteWithoutResponse)];
                 if (datalenth > 20) {
                     self.packetLength = datalenth - 20;
                 }
                NSLog(@"🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞🌞%lu",(unsigned long)datalenth);
                
                self.connectionSuccessBlock(peripheral, self.macAdress == nil ? @"00:00:00:00:00:00" : self.macAdress);
                self.macAdress = nil;
                self.connectionFailureBlock = nil;
                self.connectionSuccessBlock = nil;
            }
            else {
                NSLog(@"❌成功订阅的回调 -- 但是 self.connectionSuccessBlock && self.macAdress 不成立");
            }
        } else {
            NSLog(@"❌ 订阅失败 KSBLEManager cannot subscribe %@", characteristic);
            if (self.connectionFailureBlock) {
                self.state = KSBLEManagerStateIdle;
                NSError *e = [NSError errorWithDomain:KSBLEManagerErrorDomain code:KSBLEManagerErrorCodeCannotSubscribe userInfo:error.userInfo];
                self.connectionFailureBlock(e);
                self.connectionFailureBlock = nil;
                self.connectionSuccessBlock = nil;
            } else {
                NSLog(@"KSBLEManager连接失败前已经超时。。。");
            }
        }
    }
}

#pragma mark 收到特征的响应回调  ---------- 收到数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"KSBLEManager - 接收数据出错");
        return;
    }
    NSLog(@"🐭🐭🐭🐭🐭蓝牙原始数据回调 ==========  %@",characteristic.value);
    if ([characteristic.UUID isEqual:self.readableCharacteristics.firstObject]){
        [self getMacAddressWithPeripheral:peripheral characteristic:characteristic];
    }else{
        if ([IMTCarManager sharedCarManager].carModelType == IMCarTypeCodeR0) {
            self.receiveDataBlock(characteristic.value);
        }else {
            // 处理粘包数据 -- 有点耗能 -- 1.2ms
            NSUInteger length = [characteristic.value length];
            Byte *bytes = (Byte *) malloc(length);
            [characteristic.value getBytes:bytes length:length];
            NSUInteger index = 0;
            NSUInteger start = 0;
            for (int i = 0; i < length; i ++) {
                index ++;
                if (i > 2) {
                    uint8_t before = bytes[i - 1];
                    uint8_t next = bytes[i];
                    if ((before == 0xaa) && (next == 0xaa)) {
                        uint8_t a = bytes[i - 2];
                        uint8_t b = bytes[i+1];
                        if (i>4 && a == 0xa5 && b == 0xaa) {
                            NSLog(@"处理包尾粘包的情况 ==== 🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈🌈");
                            NSData *data = [characteristic.value subdataWithRange:NSMakeRange(start, index-1)];
                            self.receiveDataBlock(data);
                            start = index-1;
                            index = 0;
                            break;
                        }
                        NSData *data = [characteristic.value subdataWithRange:NSMakeRange(start, index-2)];
                        self.receiveDataBlock(data);
                        start = index - 2;
                        index = 0;
                    }
                }
            }
            if (start == 0) {
                self.receiveDataBlock(characteristic.value);
            }else {
                NSData *data = [characteristic.value subdataWithRange:NSMakeRange(start, length - start)];
                self.receiveDataBlock(data);
            }
        }
    }
}

#pragma mark - 获取Mac地址
- (void)getMacAddressWithPeripheral:(CBPeripheral *)peripheral characteristic:(CBCharacteristic *)characteristic{
    NSString *value = [IMFunction dataChangeToString:characteristic.value];

    if (value.length < 16) {
        return;
    }
    NSMutableString *macString = [[NSMutableString alloc] init];

    if ([peripheral.name hasPrefix:@"E2"] || [peripheral.name hasPrefix:@"E3"] || [peripheral.name hasPrefix:@"E2P"] || [peripheral.name hasPrefix:@"R0-"]) {
        [macString appendString:[[value substringWithRange:NSMakeRange(0, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(2, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(4, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(6, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(8, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(10, 2)] uppercaseString]];
    }else {
        [macString appendString:[[value substringWithRange:NSMakeRange(10, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(8, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(6, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(4, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(2, 2)] uppercaseString]];
        [macString appendString:@":"];
        [macString appendString:[[value substringWithRange:NSMakeRange(0, 2)] uppercaseString]];
    }
    self.macAdress = macString;
    NSLog(@"=====获取Mac地址：%@",self.macAdress);
}

@end

